package cn.xej.demo.condition;

import cn.xej.demo.service.AnimalService;
import cn.xej.demo.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;

import java.lang.annotation.Annotation;

/**
 * @Author alicat.xu
 * @Date 2021/11/13 10:26 下午
 */
public class AbstractCondition extends SpringBootCondition{
    private Class<? extends Annotation> annotationClass;
    private Boolean                     mock;


    public AbstractCondition(Class<? extends Annotation> annotationClass, Boolean mock) {
        this.annotationClass = annotationClass;
        this.mock = mock;
    }

    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {

        MultiValueMap<String, Object> valueMap = metadata.getAllAnnotationAttributes(annotationClass.getName());
        if (valueMap == null) {
            return new ConditionOutcome(false,"");
        }else {
            String value = (String) valueMap.get("value").get(0);
            Boolean isMock = context.getEnvironment().getProperty("mock.service." + value + ".enable", Boolean.class);
            System.out.println("class "+annotationClass+" isMock "+isMock);
            if (isMock == null){
                /**
                 * 走prod配置文件，会将真正的实现类注入到ioc容器
                 */
                isMock = context.getEnvironment().getProperty("mock.service.enable",Boolean.class);
                return new ConditionOutcome(isMock == this.mock,"");
            }else {
                /**
                 * 走mock配置文件，将mock实现类注入到ioc容器
                 */
                return new ConditionOutcome(isMock == this.mock,"");
            }
        }
    }



}
